package com.example.uhf;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;

/**
 * Created by Xysh on 2018/3/22.
 */

public class LogCatHelper {
    private static LogCatHelper instance = null;
    private String dirPath;
    private int appid;
    private Thread logThread;

    public static LogCatHelper getInstance(Context mContext, String path){
        if (null == instance){
            instance = new LogCatHelper(mContext, path);
        }
        return instance;
    }

    private  LogCatHelper(Context mContext, String path){
        appid = android.os.Process.myPid();
        if (TextUtils.isEmpty(path)){
            dirPath = mContext.getFilesDir().getAbsolutePath() + File.separator + "log";
        }else{
            dirPath = path;
        }
        File dir = new File(dirPath);
        if (!dir.exists()){
            dir.mkdirs();
        }
    }

    public void start(){
        if (null == logThread){
            logThread = new Thread(new LogRunnable(appid, dirPath));
        }
        logThread.start();
    }

    private static class LogRunnable implements Runnable{

        private Process mProcess;
        private FileOutputStream fos;
        private BufferedReader mReader;
        private String cmds;
        private String mPid;
        private String path;

        public LogRunnable(int pid, String dirPath){
            this.mPid = "" + pid;
            this.path = dirPath;
            /*
            try {
                File file = new File(dirPath, FormatDate.getFormatDate() + ".log");
                if (!file.exists()){
                    file.createNewFile();
                }
                fos = new FileOutputStream(file, true);
            }catch (Exception e){
                e.printStackTrace();
            }
            cmds = "logcat *:i | grep \"(" + mPid + ")\"";
            */
        }

        @Override
        public void run(){
            try {
                File file = new File(this.path, FormatDate.getFormatDate() + ".log");
                Log.i("Date", "DateNow      " + FormatDate.getFormatDate());
                if (!file.exists()){
                    file.createNewFile();
                }
                fos = new FileOutputStream(file, true);
                cmds = "logcat *:i | grep \"(" + mPid + ")\"";

                mProcess = Runtime.getRuntime().exec(cmds);
                mReader = new BufferedReader(new InputStreamReader(mProcess.getInputStream()),1024);
                String line;
                while((line = mReader.readLine()) != null){
                    if(line.length() == 0){
                        continue;
                    }
                    if(fos != null && line.contains(mPid)){
                        fos.write((FormatDate.getFormatTime()+" "+line+"\r\n").getBytes());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                    try {
                        fos.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if(mProcess != null){
                        mProcess.destroy();
                    mProcess = null;
                    }
                    try {
                        if(mReader != null){
                            mReader.close();
                            mReader = null;
                        }
                        if(fos != null){
                            fos.close();
                            fos = null;
                        }
                    } catch (Exception e2) {
                        e2.printStackTrace();
                    }

            }
        }
    }

    @SuppressLint("SimpleDateFormat")
    private  static class FormatDate{

        public static String getFormatDate(){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            return sdf.format(System.currentTimeMillis());
        }

        public static String getFormatTime(){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.format(System.currentTimeMillis());
        }
    }
}
